const express = require("express");
const path = require("path");
const app = express();
const http = require("http");
const ws = require("ws");
const options = {
  setHeaders: function (res, path, stat) {
    res.set("Access-Control-Allow-Origin", "*");
  }
};
app.use(express.static(path.resolve(__dirname, "public"),options));

app.use(function (req, res, next) {
  const proxy = req.query.proxy;
  if (proxy) {
    req.header.cookie = req.header.cookie + `__proxy__${proxy}`;
  }
  next();
});
/* app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
}); */
app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", req.get("Origin") || "*");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE");
  res.header("Access-Control-Expose-Headers", "Content-Length");
  res.header("Access-Control-Allow-Headers", "Accept, Authorization, Content-Type, X-Requested-With, Range");
  if (req.method === "OPTIONS") {
    return res.send(200);
  } else {
    return next();
  }
});
//获取数据 路由到不同的数据接口
app.use("/getProducts", require("./router/getProducts"));
app.use("/getProductDetail", require("./router/getProductDetail"));

const port = process.env.PORT || 3000;
//启动Http服务
let server = http.createServer(app).listen(port, () => {
  console.log(`server running @http://localhost:${port}`);
});
//创建WebSocket服务
let websocket = new ws.Server({ server: server });

//接收客户端连接
websocket.on("connection", session => {
  console.log("connection:");

  session.on("error", error => {
    console.log("client error:" + error);
  });

  session.on("close", data => {});
  //前端客户端的消息
  session.on("message", message => {
    try {
      //解析消息
      message = JSON.parse(message);
      console.log("message.type::" + message.type);
    } catch (e) {
      console.log(e.message);
    }
    //根据消息类型做不同处理
    switch (message.type) {
      //加入房间
      case "joinRoom":
        console.log("message.userId:" + message.userId);
        break;
      //离开房间
      case "leaveRoom":
        break;
      //公共聊天
      case "chat_public":
        try {
          //迭代所有Client对象发送消息
          websocket.clients.forEach(client => {
            client.send(JSON.stringify(message));
          });
        } catch (e) {
          console.log(e.message);
        }
        break;
      default:
    }
  });
});

module.exports = app;
